package xyz.hlh.boot8.controller;

import cn.hutool.json.JSONUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import xyz.hlh.boot8.common.BaseResult;
import xyz.hlh.boot8.common.Result;
import xyz.hlh.boot8.exception.CustomException;
import xyz.hlh.boot8.service.FileService;
import xyz.hlh.boot8.util.DownLoadUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @author HLH
 * @description:
 * @email 17703595860@163.com
 * @date : Created in 2021/11/20 11:00
 */
@Controller
@ResponseBody
@RequestMapping("/file")
public class FileController implements BaseResult {
    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    public ResponseEntity<?> upload(MultipartFile file) {
        if (file == null) {
            throw new CustomException(HttpStatus.BAD_REQUEST.value(), "参数错误");
        }
        Map<String, Object> result = fileService.uploadField(file);
        return success(result);
    }

    @PostMapping("/uploadBatch")
    public ResponseEntity<?> uploadBatch(MultipartFile[] files) {
        if (files == null) {
            throw new CustomException(HttpStatus.BAD_REQUEST.value(), "参数错误");
        }
        List<Map<String, Object>> result = fileService.uploadBatchField(files);
        return success(result);
    }

    @GetMapping("/download")
    public void download(String group, String filePath, String newFileName, Boolean downFlg, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isAnyBlank(group, filePath)) {
            resultException(response, HttpStatus.BAD_REQUEST, "参数错误");
        }
        ServletOutputStream os = null;
        InputStream is = null;
        try {
            if (Boolean.TRUE.equals(downFlg)) {
                String name = fileService.getFieldName(group, filePath, newFileName);
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + DownLoadUtils.getFileName(request, name));// 设置文件名
            }

            os = response.getOutputStream();
            is = fileService.download(group, filePath);
            if (is == null) {
                resultException(response, HttpStatus.NOT_FOUND, "文件不存在");
            }

            IOUtils.copy(is, os);
            os.flush();
        } catch (CustomException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            if (Boolean.TRUE.equals(downFlg)) {
                resultException(response, HttpStatus.INTERNAL_SERVER_ERROR, "文件下载失败");
            } else {
                resultException(response, HttpStatus.INTERNAL_SERVER_ERROR, "文件预览失败");
            }
        } finally {
            IOUtils.closeQuietly(os);
            IOUtils.closeQuietly(is);
        }
    }

    private void resultException(HttpServletResponse response, HttpStatus status, String errorMsg) {
        try {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(status.value());
            Result<Object> result = Result.builder().code(HttpStatus.NO_CONTENT.value()).errorMsg(errorMsg).build();
            ServletOutputStream os = response.getOutputStream();
            os.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @DeleteMapping("/delete")
    public ResponseEntity<?> delete(@RequestBody Map<String, Object> param) {
        if (!CollectionUtils.isEmpty(param)) {
            String group = param.get("group") == null ? null : String.valueOf(param.get("group"));
            String filePath = param.get("filePath") == null ? null : String.valueOf(param.get("filePath"));
            if (StringUtils.isAnyBlank(group, filePath)) {
                throw new CustomException(HttpStatus.BAD_REQUEST.value(), "参数错误");
            }
            fileService.deleteFile(group, filePath);
        }
        return success(null);
    }

    @DeleteMapping("/deleteBatch")
    public ResponseEntity<?> deleteBatch(@RequestBody Map<String, Object> param) {
        try {
            if (!CollectionUtils.isEmpty(param)) {
                for (Map.Entry<String, Object> entry : param.entrySet()) {
                    String group = entry.getKey();
                    List<String> filePathList = (List<String>) entry.getValue();
                    for (String filePath : filePathList) {
                        fileService.deleteFile(group, filePath);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.OK).body(null);
    }

}
